<template>
  <BaseDialog :loading="loading" width="605px" destroy-on-close @confirm="save" @close="close" confirmText="保存" v-model="isShow"
              title="设置角色">
    <el-transfer :titles="['全部角色','已有角色']" :props="{key: 'roleId',label: 'roleName',disabled: 'disabled' }" v-model="roles" :data="data"/>
  </BaseDialog>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {DictDataModel} from "/@/api/system/model/DictModel";
import {listRoleAll} from "/@/api/system/RoleApi";
import {RoleModel} from "/@/api/system/model/RoleModel";
import {ENABLED} from "/@/utils/dict/Dict";
import {listUserRoleByUserId, saveUserRole} from "/@/api/system/UserApi";


const isShow = ref(false)
const data = ref<RoleModel[]>([])
const roles = ref<string[]>([])
const loading = ref(false)
const userId = ref()
const dataType = ref<DictDataModel[]>([])
const init = async (userIdValue) => {
  userId.value = userIdValue
  await loadRoleAll()
  await listUserRole()
  isShow.value = true
}
const save = async () => {
  loading.value = true
  await saveUserRole({userId: userId.value, roleIds: roles.value},()=>{
    loading.value = false
  })
  close()
}
const loadRoleAll = async () => {
  let res = await listRoleAll();
  if (res && res.length > 0) {
    res.forEach(res => {
      res.disabled = res.enabled === ENABLED.NO
    })
  }
  data.value = res
}
const listUserRole = async () => {
  let res = await listUserRoleByUserId(userId.value);
  if(res && res.length > 0){
    roles.value = res.map(res=> res.roleId)
  }

}
const close = () => {
  isShow.value = false
}
defineExpose({init})
</script>

<style scoped>

</style>